import org.omg.CORBA.RepositoryIdHelper;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Socket;
import java.net.SocketException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2022-11-01
 * Time: 21:39
 */
public class UdpEchoServer {
    public DatagramSocket socket;

    //udp的服务器需要自己指定端口号
    public UdpEchoServer(int port) throws SocketException {
        socket=new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("启动服务器");
        while(true){
            //三个步骤
            //1.接受客户端发来的请求
            //先构造出数据报(盘子)
            DatagramPacket requestPacket=new DatagramPacket(new byte[1024],1024);
            //接收数据
            socket.receive(requestPacket);//输出型参数
            //将数据报解析成一个字符串
            String request=new String(requestPacket.getData(),0,
                    requestPacket.getLength(),"UTF-8");//注意这里求的长度直接用的是数据报
            //2.根据请求计算出响应
            String response=process(request);
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),
                    response.getBytes().length,//注意长度是字节数组的长度
                    requestPacket.getSocketAddress());//注意要加上IP地址和端口,这里合起来写了
            //3.响应返回给客户端
            socket.send(responsePacket);
            System.out.printf("[reqIP:%s  req端口号:%d][req:%s  resp:%s]\n",requestPacket.getAddress().toString(),
                    responsePacket.getPort(),request,response);
        }
    }
    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws SocketException {
        UdpEchoServer udpEchoServer=new UdpEchoServer(9090);
        try {
            udpEchoServer.start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
